package com.papper.mng.controller.sys;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import com.papper.common.bean.sys.SysPageConfig;
import com.papper.common.bean.sys.SysSystem;
import com.papper.common.bean.sys.SysUser;
import com.papper.common.config.SysSystemHelp;
import com.papper.common.constant.SystemConstants;
import com.papper.common.enums.DataStatusEnum;
import com.papper.common.exception.ServiceException;
import com.papper.common.service.DwzPage;
import com.papper.common.service.sys.SysPageConfigService;
import com.papper.common.utils.tool.StringTool;
import com.papper.mng.controller.BaseAction;
import com.papper.mng.domain.DwzResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author:LaJiao
 * @Date:2019-07-17 15:27:38
 * @Description:系统页面配置
 */
@Controller
@RequestMapping("/sys/page/config")
public class SysPageConfigAction extends BaseAction {
    @Autowired
    SysPageConfigService sysPageConfigService;

    /**
     * 系统页面配置
     *
     * @return
     */
    @RequestMapping(value = "")
    public String execute(HttpServletRequest _request, HttpServletResponse _response, Model model) {
        // 字段查询条件
        Map<String, Object> objects = Maps.newHashMap();
        extraParams(objects, _request, SysPageConfig.class);
        modelParm(objects, model);
        // 分页查询条件
        int pageNum    = StringTool.parseInteger(_request.getParameter("pageNum"), 1);
        int numPerPage = StringTool.parseInteger(_request.getParameter("numPerPage"), SystemConstants.PAGE_LIMIT_20);
        // 数据查询组装
        Example                 example = buildExample(objects, model, SysPageConfig.class);
        PageInfo<SysPageConfig> pageRtn = sysPageConfigService.findPage(pageNum, numPerPage, example);
        model.addAttribute("page", new DwzPage(pageNum, numPerPage, pageRtn.getTotal()));
        model.addAttribute("records", pageRtn.getList());
        return render("sys/page/config/index");
    }

    /**
     * 系统页面配置_新增
     *
     * @param _response
     * @
     */
    @GetMapping(value = "/add")
    public String add_get(HttpServletResponse _response, Model model) {
        return render("sys/page/config/add");
    }

    @PostMapping(value = "/add")
    @ResponseBody
    public DwzResponse add_post(HttpServletRequest _request, HttpServletResponse _response, SysPageConfig sysPageConfig) {
        try {
            checkVerifyCert(_request);
        } catch (ServiceException e) {
            return new DwzResponse("300", e.getMessage());
        }

        // 添加系统页面配置
        try {
            sysPageConfig.setDataStatus(DataStatusEnum.OPEN.getCode());
            sysPageConfig.setCreateTime(new Date());
            sysPageConfig.setModifyTime(new Date());
            sysPageConfigService.save(sysPageConfig);
            return new DwzResponse("200", "系统页面配置添加成功!!!", "closeCurrent");
        } catch (Exception e) {
            e.printStackTrace();
            return new DwzResponse("300", "系统页面配置添加失败:" + e.getMessage() + "!!!");
        }
    }

    /**
     * 系统页面配置_更新
     *
     * @param pageCode
     * @param fields
     * @
     */
    @GetMapping(value = "/edit")
    public String edti_get(Model model, String pageCode, String fields) {
        SysUser             sysUser      = getLoginUser();
        SysSystem           sysSystem    = SysSystemHelp.I().sys();
        SysPageConfig       entity       = sysPageConfigService.findByPaygeCode(sysSystem.getSystemCode(), sysUser.getId().toString(), pageCode);
        Map<String, String> fieldsConfig = Maps.newHashMap();
        if (entity != null) {
            JSONObject pageConfig = JSON.parseObject(entity.getPageConfig());
            for (String k : pageConfig.keySet()) {
                fieldsConfig.put(k, pageConfig.getString(k));
            }
        }
        model.addAttribute("sysSystem", sysSystem);
        model.addAttribute("pageCode", pageCode);
        model.addAttribute("fieldsConfig", fieldsConfig);
        List<String> fieldArray = Splitter.on(',').trimResults().omitEmptyStrings().splitToList(fields);
        model.addAttribute("fieldArray", fieldArray);
        return render("sys/page/config/edit");
    }

    @PostMapping(value = "/edit")
    @ResponseBody
    public DwzResponse edit_post(HttpServletRequest _request, String pageCode, String fields) {
        try {
            checkVerifyCert(_request);
        } catch (ServiceException e) {
            return new DwzResponse("300", e.getMessage());
        }
        SysUser       sysUser   = getLoginUser();
        SysSystem     sysSystem = SysSystemHelp.I().sys();
        SysPageConfig entity    = sysPageConfigService.findByPaygeCode(sysSystem.getSystemCode(), sysUser.getId().toString(), pageCode);
        if (entity == null) {
            entity = new SysPageConfig();
            entity.setSystemCode(sysSystem.getSystemCode());
            entity.setUserId(sysUser.getId().intValue());
            entity.setPageCode(pageCode);
            entity.setPageConfig(matchFields(fields).toJSONString());
            entity.setDataStatus(DataStatusEnum.OPEN.getCode());
            entity.setCreateTime(new Date());
            entity.setModifyTime(new Date());
            try {
                sysPageConfigService.save(entity);
                return new DwzResponse("200", "系统页面配置修改成功!!!", "closeCurrent");
            } catch (Exception e) {
                e.printStackTrace();
                return new DwzResponse("300", "系统页面配置修改失败:" + e.getMessage());
            }
        } else {
            entity.setPageConfig(matchFields(fields).toJSONString());
            entity.setModifyTime(new Date());
            try {
                sysPageConfigService.update(entity);
                return new DwzResponse("200", "系统页面配置修改成功!!!", "closeCurrent");
            } catch (Exception e) {
                e.printStackTrace();
                return new DwzResponse("300", "系统页面配置修改失败:" + e.getMessage());
            }
        }
    }

    private JSONObject matchFields (String fields) {
        JSONObject   fieldsJson = new JSONObject();
        List<String> fieldArray = Splitter.on(',').trimResults().omitEmptyStrings().splitToList(fields);
        if (fieldArray != null) {
            for (String s : fieldArray) {
                String[] ss = s.split("_");
                if (ss.length != 2) {
                    continue;
                }
                fieldsJson.put(ss[0], ss[1]);
            }
        }
        return fieldsJson;
    }

    /**
     * 系统页面配置_删除
     *
     * @param id
     * @
     */
    @PostMapping(value = "/del")
    @ResponseBody
    public DwzResponse del_post(HttpServletRequest _request, Long id) {
        try {
            checkVerifyCert(_request);
        } catch (ServiceException e) {
            return new DwzResponse("300", e.getMessage());
        }
        if (id == null || id.intValue() <= 0) {
            return new DwzResponse("300", "参数[id]为空！");
        }
        SysPageConfig old = sysPageConfigService.findById(id);
        if (old == null) {
            return new DwzResponse("300", "参数[id]信息异常！");
        }
        try {
            sysPageConfigService.deleteById(id);
            return new DwzResponse("200", "系统页面配置删除成功!!!");
        } catch (Exception e) {
            e.printStackTrace();
            return new DwzResponse("300", "系统页面配置删除失败:" + e.getMessage());
        }
    }

    /**
     * 系统页面配置_详情
     *
     * @return
     */
    @GetMapping(value = "/detail")
    public String detail(HttpServletResponse _response, Model model, Long id) {
        SysPageConfig sysPageConfig = sysPageConfigService.findById(id);
        model.addAttribute("entity", sysPageConfig);
        return render("sys/page/config/detail");
    }
}